
var passengerWin, driverWin;
var driverLatLng, oldLatLng, setTimeOutFunc, continueTrace = true;
var distance;
var directionsDisplay, directionsService;
var allowOrder = false;
var fromAddrLat, fromAddrLng, toAddrLat, toAddrLng, latlng;
var fromInfowindow = null; 
var toInfowindow = null;
var fromMarker = null;
var toMarker = null;
var bounds;
var INFOBOXCSSTEXT = "border: 1px solid black; margin-top: 8px; background: white; padding: 5px;";
//customer-main.html is a multi-use page, with 3 pages: customer-main (cusmain or custMain), response (response)
//and real-time(realTime). The pages move like this: custMain-->loading-->response-->realTime

//customer-main displays: a map with current position and drivers, with options to call now, or book taxi.

//response displays: a map with current position and the selected driver ONLY, with an option to accept or decline
// It also displays driver information

//realTime (only if customer accepted): a map with current position and selected driver's position, updated in real time
// displays driver information

(function($){
	if(window.page == 0){
		$(".cusmain").removeClass("hidden");
		$(".cusmainheader").removeClass("hidden");
		$(".dispOptions").removeClass("hidden");
		$(".response").addClass("hidden");
		$(".responseheader").addClass("hidden");
		$("#mapContainer").addClass("custMainMap");
		$("#mapContainer").removeClass("responseMap");
		$(".orderTaxi").addClass("hidden");
	}
	else if(window.page == 1){
		$(".cusmain").addClass("hidden");
		$(".dispOptions").addClass("hidden");
		$(".response").removeClass("hidden");
		$(".responseheader").removeClass("hidden");
		$("#mapContainer").removeClass("custMainMap");
		$("#mapContainer").addClass("responseMap");
		$(".orderTaxi").addClass("hidden");
		//initializes the elements required for driver location and information
		
		setTimeout(function() {
			window.initializeOtherElement(window.map);
		}, 6000);
		

	}else if(window.page == 2){
		alert("window.page==2");
		$(".cusmain").addClass("hidden");
		$(".cusmainheader").addClass("hidden");
		$(".dispOptions").addClass("hidden");
		$(".response").removeClass("hidden");
		$(".responseheader").removeClass("hidden");
		$("#mapContainer").removeClass("custMainMap");
		$("#mapContainer").addClass("responseMap");
		$(".orderTaxi").addClass("hidden");
		window.backDriInfo = {};
		window.backDriInfo.driverInfo = {};
		window.backDriInfo.driverInfo.id = window.backResult.driverInfo.id;
		realtime();	
	}
	
	doSubscribe();
})(jQuery);

//---------------------------customer-main-----------------------------------

/**
 * function that changes to loading page
 * 
 */
function changeToLoading(){
	window.custOption = $("input:radio[name=options]:checked").val();
	jQuery.mobile.changePage("../view/loading.html");
	
}

/**
 * changes the function of the bookNowBtn to display a popup
 * that does not allow the person to call again
 */
var switchPopup = function(){
	$("#bookNowBtn").attr("data-rel", "popup");
	$("#bookNowBtn").attr("href", "#noOrderPopup");
	$("#bookNowBtn").off("click", changeToLoading);
};


/**
 * Gives the bookNowBtn function to hail taxis again
 * removes its attributes for displaying the popup
 */
var switchLoading = function(){
	$("#bookNowBtn").removeAttr("data-rel");
	$("#bookNowBtn").removeAttr("href");
	$("#bookNowBtn").on("click", changeToLoading);
	window.polylineList.length = 1;
	//this book now process end, clean the json store of this cus_id, dri_id
	window.audioJS.remove({cus_id: window.customer.id, dri_id: window.backResult.driverInfo.id}, {})
	.then(function (numberOfDocumentsRemoved) {
//	    alert("numberOfDocumentsRemoved:::" + numberOfDocumentsRemoved);
	})
	.fail(function (errorObject) {
	    alert("remove fail");
	});
};



//sets event handlers for the custMain menu and buttons
$("#backToCusmain").on("click", backToCustmain);
$("#curOrdersLink").on("click", function(){
	jQuery.mobile.changePage("../view/info-center.html");
});

$("#orderHistLink").on("click", function(){
	jQuery.mobile.changePage("../view/info-center.html");
});
$("#myCreditLink").on("click", function(){
	//jQuery.mobile.changePage("../view/myCurOrders.html");
});

//$("#acceptBtn").on("click", function(){
//	changeToOrderTaxi();
//});

$("#bookNowBtn").on("click", changeToLoading);
$("#orderTaxiBtn").on("click", changeToOrderTaxi);

function doSubscribe(){
	alert("doSubscribe");
	WL.Client.Push.subscribe("myPush", {
		onSuccess: doSubscribeSuccess,
		onFailure: doSubscribeFailure
	});
}

//add the basic function to deal with notification in client
function doSubscribeSuccess(response){
	alert("doSubscribeSuccess");
	
	//push notification responses are two kinds: order and voice
	var result = new Object();
	// result = response.     ......
	
	if ( result.Pkind == '0'){
		//deal with the order info
		
	}else if ( result.Pkind == '1'){
		//deal with the voice 
//		receiveEncodeAudio(cus_id, dri_id, recordTime, result.encodedString);
	}
	
}

function doSubscribeFailure(){
	alert("doSubscribeFailure");
}
$("#submitBtn").on("click", submitOrder);

//--------------------------- changeToOrderTaxi ----------------------------------
function changeToOrderTaxi() {
	
	$(".cusmain").addClass("hidden");
	$(".response").addClass("hidden");
	$(".responseheader").addClass("hidden");
	$("#mapContainer").removeClass("custMainMap");
	$("#mapContainer").addClass("orderTaxiMap");
	$(".orderTaxi").removeClass("hidden");
	$(".cusmainheader").addClass("hidden");
	$("#radioBackground").addClass("hidden");
	$("#submitOrderBtn").on("click", submitOrder);
	initializeAutocomplete();
	window.markerPassenger.setVisible(false);
	driverWin.close();
	if(window.polylineList!=null || window.polylineList.length != 0) {
//		alert("order poly[0] ==2");
		window.markerDriver.setVisible(false);
		directionsDisplay.setMap(null);
		window.polylineList[0] = 2;
		for(var i = 1; i < polylineList.length; i++ ) {
			polylineList[i].setVisible(false);
		}
	}
}

function submitOrder() {
	var setupTimeInput = $('#slider_example_3');
	var fromAddrInput = $('#fromAddr');
	var toAddrInput = $('#toAddr');
	setupTimeInput.change(function() {
		$('#orderInputs div:first-child').css('background-color', 'white');
	});
	
	
	var canSubmit = true;
	if(setupTimeInput.val() == null || setupTimeInput.val() == "") {
		$('#orderInputs div:first-child').css('background-color', '#FFEB00');
		setupTimeInput.attr('placeholder', 'when will you go ?');
		canSubmit = false;
	}
	if(fromAddrLat == null || fromAddrLat == undefined) {
		$('#orderInputs div:nth-child(2)').css('background-color', '#FFEB00');
		fromAddrInput.attr('placeholder', 'where will you set up from ?');
		fromAddrInput.focus(function() {
			$('#orderInputs div:nth-child(2)').css('background-color', 'white');
		});
		canSubmit = false;
	}
	if(toAddrLng == null || toAddrLat == undefined) {
		$('#orderInputs div:nth-child(3)').css('background-color', '#FFEB00');
		toAddrInput.attr('placeholder', 'when will you go ?');
		toAddrInput.focus(function() {
			$('#orderInputs div:nth-child(3)').css('background-color', 'white');
		});
		canSubmit = false;
	}
	if(canSubmit) {
		var invocationData = {
				adapter : 'stAdp',
				procedure : 'orderTaxi',
				parameters : [{'cus_id': window.customer.id,'setupTime':setupTimeInput.val(),'fromAddrLat':fromAddrLat,'fromAddrLng':fromAddrLng, 'toAddrLat': toAddrLat, 'toAddrLng':toAddrLng}]
		};
		busy.show();
		WL.Client.invokeProcedure(invocationData, {
			onSuccess : orderTaxiSuccess,
			onFailure : orderTaxiFailure
		});
	}
	
}

function orderTaxiSuccess() {
	busy.hide();
//	alert("order success.");
	backToCustmain();
	setTimeout(function() {
		var d = {name: "Jane Zheng", credit: 4, color: "blue", license: "ST1123"};
		var o = {time: "08/21/2013 11:00", fromAddr: "中国上海市上海浦东新区张江", toAddr: "中国火车站上海火车站"};
		receiveOrderAccept(d, o);
	}, 2000);
}

function orderTaxiFailure() {
	busy.hide();
	alert("order failure.");
	backToCustmain();
//	window.showToast("sorry , order failure.");
}


function backToCustmain() {
//	window.page = 0;
	$(".cusmain").removeClass("hidden");
	$(".cusmainheader").removeClass("hidden");
	$(".dispOptions").removeClass("hidden");
	$(".response").addClass("hidden");
	
	if(window.page == 1) {
		$(".responseheader").removeClass("hidden");
	}
	$("#mapContainer").removeClass("orderTaxiMap");
	$("#mapContainer").addClass("custMainMap");
	$(".orderTaxi").addClass("hidden");

//	alert("window.marker passage show");
	window.markerPassenger.setVisible(true);
	window.map.setCenter(window.passengerLatLng);
//	alert("frommarker hide");
	fromMarker.setVisible(false);
//	alert("to marker hide");
	toMarker.setVisible(false);
//	alert("from infowindow close");
	fromInfowindow.close();
//	alert("to info window close");
	toInfowindow.close();

	if(window.polylineList != null && window.polylineList.length != 0) {
//		alert("window.marker driver show");
		window.markerDriver.setVisible(true);
		directionsDisplay.setMap(window.map);
//		alert("polyline[0]=2");
		window.polylineList[0] = 1;
		for(var i = 1; i < polylineList.length; i++ ) {
			polylineList[i].setVisible(true);
		}
	}
}

function initializeAutocomplete() {
	var fromInput = /** @type {HTMLInputElement} */
	(document.getElementById('fromAddr'));
	var toInput = /** @type {HTMLInputElement} */
	(document.getElementById('toAddr'));
	var fromAutocomplete = new google.maps.places.Autocomplete(fromInput);
	var toAutocomplete = new google.maps.places.Autocomplete(toInput);
	fromAutocomplete.bindTo('bounds', window.map);
	toAutocomplete.bindTo('bounds', window.map);
	
//	alert("fromInfowindow==null::" + (fromInfowindow==null) );
	fromInfowindow = new google.maps.InfoWindow();

//	fromInfowindow = createInfobox(100);

	fromMarker = new google.maps.Marker({
		map : window.map
	});
//	alert("fromInfowindow==null::" + (fromInfowindow==null) );
//	alert("frommarker==null::" + (fromMarker==null) );
	
//	alert("toInfowindow==null::" + (toInfowindow==null) );
//	alert("toMarker==null::" + (toMarker==null));
	toInfowindow = new google.maps.InfoWindow();

//	toInfowindow = createInfobox(100);

	toMarker = new google.maps.Marker({
		map : window.map
	});
	
	google.maps.event.addListener(fromAutocomplete, 'place_changed', function() {

		fromInfowindow = new google.maps.InfoWindow();
//	    fromMarker.setVisible(false);


//		fromInfowindow.close();
	    fromMarker.setVisible(false);

	    var place = fromAutocomplete.getPlace();
	    if (!place.geometry) {
	      return;
	    }
	    // If the place has a geometry, then present it on a map.
	    if (place.geometry.viewport) {
	      window.map.fitBounds(place.geometry.viewport);
	    } else {
	      window.map.setCenter(place.geometry.location);
	      window.map.setZoom(17);  // Why 17? Because it looks good.
	    }
	    fromMarker.setIcon(/** @type {google.maps.Icon} */({
	      url: place.icon,
	      size: new google.maps.Size(71, 71),
	      origin: new google.maps.Point(0, 0),
	      anchor: new google.maps.Point(17, 34),
	      scaledSize: new google.maps.Size(35, 35)
	    }));
	    latlng = place.geometry.location;
//	    alert(latlng);
	    fromMarker = new google.maps.Marker({
			map : window.map,
			position: latlng 
		});
//	    alert(fromMarker);
	    fromAddrLat = latlng.lat();
	    fromAddrLng = latlng.lng();
	    fromMarker.setPosition(latlng);
//	    alert(fromMarker.getVisible());
	    fromMarker.setVisible(true);
//	    alert("check4");
	   
	    
	    var address = '';
	    if (place.address_components) {
	      address = [
	        (place.address_components[0] && place.address_components[0].short_name || ''),
	        (place.address_components[1] && place.address_components[1].short_name || ''),
	        (place.address_components[2] && place.address_components[2].short_name || '')
	      ].join(' ');
	    }

	    var content = document.createElement("div");
//	    content.style.cssText = INFOBOXCSSTEXT;
	    content.innerHTML = "<strong>" + place.name + "</strong><br>" + address;
	    fromInfowindow.setContent(content);
//	    alert("from infowindow oopen");
	    fromInfowindow.open(window.map, fromMarker);

//	    var content = document.createElement("div");
//	    content.style.cssText = INFOBOXCSSTEXT;
//	    content.innerHTML = "<strong>" + place.name + "</strong><br>" + address;
//	    fromInfowindow.setContent(content);
//	    fromInfowindow.open(window.map, fromMarker);
	    var toMarkerPos = toMarker.getPosition();
	    if(toMarkerPos != null){
	    	var fromMarkerPos = fromMarker.getPosition();
	    	setBounds(toMarkerPos, fromMarkerPos);
	    }
	});
	
//	alert("addListener from");
	google.maps.event.addListener(toAutocomplete, 'place_changed', function() {
//		toInfowindow.close();
//	    toMarker.setVisible(false);
	    var place = toAutocomplete.getPlace();
	    if (!place.geometry) {
	      return;
	    }
	    // If the place has a geometry, then present it on a map.
	    if (place.geometry.viewport) {
	      window.map.fitBounds(place.geometry.viewport);
	    } else {
	      window.map.setCenter(place.geometry.location);
	      window.map.setZoom(17);  // Why 17? Because it looks good.
	    }
	    toMarker.setIcon(/** @type {google.maps.Icon} */({
	      url: place.icon,
	      size: new google.maps.Size(71, 71),
	      origin: new google.maps.Point(0, 0),
	      anchor: new google.maps.Point(17, 34),
	      scaledSize: new google.maps.Size(35, 35)
	    }));
	    latlng = place.geometry.location;
	    toAddrLat = latlng.lat();
	    toAddrLng = latlng.lng();
	    
	    toMarker.setPosition(place.geometry.location);
	    toMarker.setVisible(true);
	    var address = '';
	    if (place.address_components) {
	      address = [
	        (place.address_components[0] && place.address_components[0].short_name || ''),
	        (place.address_components[1] && place.address_components[1].short_name || ''),
	        (place.address_components[2] && place.address_components[2].short_name || '')
	      ].join(' ');
	    }

	    var content=document.createElement("div");
//	    content.style.cssText = INFOBOXCSSTEXT;
	    content.innerHTML = "<strong>" + place.name + "</strong><br>" + address;
	    toInfowindow.setContent(content);
//	    alert("to infowindow open");
	    toInfowindow.open(window.map, toMarker);

//	    var content=document.createElement("div");
//	    content.style.cssText = INFOBOXCSSTEXT;
//	    content.innerHTML = "<strong>" + place.name + "</strong><br>" + address;
//	    toInfowindow.setContent(content);
//	    toInfowindow.open(window.map, toMarker);
	    var fromMarkerPos = fromMarker.getPosition();
	    if(fromMarkerPos != null){
	    	var toMarkerPos = toMarker.getPosition();
	    	setBounds(toMarkerPos, fromMarkerPos);
	    }
	  });
	//alert("autocomplete initialized");
}


//---------------------------response----------------------------------------

window.initializeOtherElement = function(map) {
	
	// Use the driver's information and place it into html
	
	initializeDriverInfo();
	
	// initialize event handlers for the buttons
	
	initializeListener();
	
	//get driver's position from the variables imported by the server and create a marker there
	driverLatLng = new google.maps.LatLng(window.backResult.driverInfo.lat, window.backResult.driverInfo.lng);
//	driverLatLng = new google.maps.LatLng(window.passengerLatLng.lat() + 0.001, window.passengerLatLng.lng() + 0.001);
	window.markerDriver = initializeMarker(driverLatLng, window.map);

	driverWin = new google.maps.InfoWindow();
	var content = "<p>distance:  <strong>" + window.backResult.distance +"</strong></p><p>time:  <strong>" + window.backResult.saveTime + "</strong></p>";
	driverWin.setContent(content);
	driverWin.open(window.map, window.markerDriver);
    
	setBounds(driverLatLng, window.passengerLatLng);

	// Draw and find the directions between the passenger and driver
	initializeDirections();
	
	//find distance between passenger and driver

};

/* 
 * Create a marker on the specified map
 * returns the set marker
 */
function initializeMarker(latlng, map) {
	marker = new google.maps.Marker({
		map: map,
		visible: true,
		draggable: true,
		animation: google.maps.Animation.DROP,

		position: latlng,
		icon: "../images/cabMarker.png",
		position: latlng,
		icon: {
			url: "../images/cabMarker.png",
			scaledSize: new google.maps.Size(30,30),
		},
		shadow: {
			url: "../images/cabMarkerShadow.png",
			scaledSize: new google.maps.Size(60,30),
			anchor: google.maps.Point(30,30)
		}
	});
	return marker;
}

/**
 * initialize driver info in $("driverInfo")
 */
function initializeDriverInfo() {
//	alert(JSON.stringify(window.backResult.driverInfo));
	$("#driphoto").attr("src", window.backResult.driverInfo.photo);
	$("#name").text(window.backResult.driverInfo.name);
	$("#license").text(window.backResult.driverInfo.license);
	$("#color").text(window.backResult.driverInfo.color);
	var credit = window.backResult.driverInfo.credit;
	for(var i = 0; i < credit; i++) {
		$("<img src='../images/star.png' width='14px' height='14px' />").appendTo($("#credit"));
	}
}

/**
 * initialize the variables required to display driving directions
 */
function initializeDirections(){
	directionsDisplay = new google.maps.DirectionsRenderer({
		suppressMarkers:true,
	});
	directionsDisplay.setMap(window.map);
	calcRoute();
}

/**
 * Call google to calculate the driver route and display the route
 */
function calcRoute(){
	directionsService = new google.maps.DirectionsService();
	var request={
		origin: driverLatLng,
		destination: window.passengerLatLng,
		travelMode:google.maps.TravelMode.DRIVING
	};

	directionsService.route(request, function(response, status){

		if(status==google.maps.DirectionsStatus.OK){

			directionsDisplay.setDirections(response);

		}
	});
}
/*
 * Attach event handlers to accept and refuse buttons 
 * 
 */
function initializeListener() {
	$('#acceptBtn').on('tap', function(){
		var invocationData = {
				adapter : 'stAdp',
				procedure : 'sendAcceptReq',
				parameters : [{'dri_id' : window.backResult.driverInfo.id, 'cus_id': window.customer.id}]
		};
		busy.show();
//		alert("busy show");
//		alert(window.backResult.driverInfo.id + " " + window.customer.id);
		WL.Client.invokeProcedure(invocationData, {
			onSuccess : acceptSuccess,
			onFailure : acceptFailure
		});
		
		//add the hide action to voicecontainer to improve ux
		$('#voicecontainer').hide();
	});
	$('#refuseBtn').on('tap', function(){
		var invocationData = {
				adapter : 'stAdp',
				procedure : 'sendRefuseReq',
				parameters : [{'dri_id' : window.backResult.driverInfo.id, 'cus_id': window.customer.id}]
		};
		busy.show();
		WL.Client.invokeProcedure(invocationData, {
			onSuccess : refuseSuccess,
			onFailure : refuseFailure
		});
	});
}

function acceptSuccess(result) {
//	alert("acceptSuccess");
	busy.hide();
	
	// imports results into global window variables
	
	window.backResult=result.invocationResult;
	window.backResult.driverInfo=result.invocationResult.dri_info;
	window.backDriInfo.driverInfo.id = window.backResult.driverInfo.id;
	window.backDriInfo.driverInfo.lat = window.backResult.driverInfo.lat;
	window.backDriInfo.driverInfo.lng = window.backResult.driverInfo.lng;
	window.backResult.distance = result.invocationResult.distance;
	window.backResult.saveTime = result.invocationResult.saveTime;
	var data = {cus_id: window.customer.id, dri_id: window.backResult.driverInfo.id};
	window.bookNowState.add(data, {onSuccess: function(){
//		alert("insert success");
	}, onFailure: function(){alert("insert fail");}});
	//starts up the real-time page
	realtime();	
}

function acceptFailure(result) {
	alert("error");
}

/**
 * if refused, it changes back to the customer's main page
 */
function refuseSuccess(result) {
	busy.hide();
	window.page=0;
	$.mobile.changePage("../view/customer-main.html");
}

function refuseFailure(result) {
	busy.hide();
	window.page=0;
	alert("fail");
	$.mobile.changePage("../view/customer-main.html");
}
//--------------------------------real-time-------------------------------------------------

function realtime(){
	$(".cusmain").removeClass("hidden");
	$(".response").addClass("hidden");
	$("#radioBackground").removeClass("hidden");
	switchPopup();
//	
	setInitPosition();
	
//	$("#mapContainer").on('tap', function() {
//		driverWin.setContent("<p>distance:" + window.backDriInfo.distance + "</p><p>saveTime:" + window.backDriInfo.saveTime + "</p>");
//		driverWin.open(window.map, markerDriver);
//		setTimeout(function() {
//		      driverWin.close();
//		}, 2000);
//	});
}

function setInitPosition() {
//	alert("dri_id:" + window.backDriInfo.driverInfo.id + " cus_id:" + window.customer.id);
	var invocationData = {
			adapter : 'stAdp',
			procedure : 'getDriverRealTimePosition',
			parameters : [{'dri_id' : window.backDriInfo.driverInfo.id, 'cus_id' : window.customer.id}]
	};
	WL.Client.invokeProcedure(invocationData, {
		onSuccess : setInitPositionSuccess,
		onFailure : getPositionFailure
	});
}

function setInitPositionSuccess(result) {
	var myResult = result.invocationResult;
	var currentLat = myResult.dri_info.lat;
	var currentLng = myResult.dri_info.lng;
	window.backDriInfo.distance = myResult.distance;
	window.backDriInfo.saveTime = myResult.saveTime;
	driverLatLng = new google.maps.LatLng(currentLat, currentLng);
	window.markerDriver.setPosition(driverLatLng);
	window.polylineList = [];
	//1 for book now, 2 for order
	window.polylineList[0] = 1;
	setTimeout(function() {
        realTimeMove();
  }, 500);
	//add infobox here
}

function realTimeMove() {
	if(continueTrace) {	
		oldLatLng = driverLatLng;
		
		var invocationData = {
				adapter : 'stAdp',
				procedure : 'getDriverRealTimePosition',
				parameters : [{'dri_id' : window.backDriInfo.driverInfo.id, 'cus_id' : window.customer.id}]
		};
		WL.Client.invokeProcedure(invocationData, {
			onSuccess : getPositionSuccess,
			onFailure : getPositionFailure
		});
	} else {
//		alert("cleartimeout");
		window.setTimeout(function(){
			switchLoading();
		}, 5000);
		
		clearTimeout(setTimeOutFunc);
	}
}

function getPositionSuccess(result) {
	var myResult = result.invocationResult;
	var currentLat = myResult.dri_info.lat;
	var currentLng = myResult.dri_info.lng;
	window.backResult.distance = myResult.distance;
	window.backResult.saveTime = myResult.saveTime;
	driverLatLng = new google.maps.LatLng(currentLat, currentLng);
	window.markerDriver.setPosition(driverLatLng);
//	alert("currentLat" + currentLat);
	var points = [oldLatLng, driverLatLng];
	var mypath = new google.maps.Polyline({
		path:points,
		strokeColor:"red",
		strokeOpacity: .4,
		strokeWeight: 5,
		map: map,
		visible: true
	});
	if(window.polylineList[0] == 2) {
		mypath.setVisible(false);
	}
	window.polylineList.push(mypath);
	// Calculate distance between passenger and driver
	var currentDistance = google.maps.geometry.spherical.computeDistanceBetween(window.passengerLatLng, driverLatLng);
	if(currentDistance < 50){
		continueTrace = false;
	}
	setTimeOutFunc = setTimeout("realTimeMove()", 1000);
}
/**
 * get driver position request fail 
 */
function getPositionFailure(result) {
	alert("fail");
	setTimeOutFunc = setTimeout("realTimeMove()", 1000);
}


/**
 * 
 * @param msg (string)
 * @param width (int)
 * @param marker (google.maps.Marker)
 */
function createInfobox(width){
	var offset = width/2 * -1;
	var options = {
           disableAutoPan: false,
           pixelOffset: new google.maps.Size(offset, 0),
           boxStyle: { 
				opacity: 0.9,
				width: width + "px"
            },
           closeBoxMargin: "10px 2px 2px 2px",
           isHidden: false,
           pane: "floatPane",
           enableEventPropagation: false
           
	};
	return new InfoBox(options);
}

//------------------------------------- record -----------------------------
var recordMedia = null;
//html element
var loadingRecord = null;
var recordSrc = "record.ogg";
var playSrc = "play.ogg";
$("#microphoto").on('tap',function(){
	initVoicePanel();
	$("#voicecontainer").slideToggle("slow");
});

/**
 * initialize the voice container panel, take out lastest 6 records which have the biggest record time
 */
function initVoicePanel() {
	var status = $("#voicecontainer").css('display');
	if(status != "none") {
//		alert("none");
		return;
	}
//	alert(document.getElementById('recordHistory').childElementCount);
	if(document.getElementById('recordHistory').childElementCount != 0) {
//		alert("has child");
		return;
	}
	var findAllSuccess = function(data) {
		$.each(data, function(i, obj) {
			var record = obj.json;
			var objid = obj._id;
//			alert(record.cus_id + " " + record.dri_id);
//			alert(window.customer.id +  " " + window.backResult.driverInfo.id);
			var dateTime = new Date();
			dateTime.setTime(record.recordTime);
			var timeString = dateTime.getFullYear() + "/" + dateTime.getMonth() + "/" + dateTime.getDate() + " " + dateTime.getHours() + ":" + dateTime.getMinutes() + ":" + dateTime.getSeconds();
//			alert(timeString);
			
			if(record.dri_id == 0 && record.cus_id == window.customer.id) {
				//the current user is costomer
				var right = $("<div class='right'><span class='triangle-border right'>" + timeString + "</span><img src='../images/defaultPhoto.png' width='40px' height='40px'></div>");
				right.on('tap', function() {playRecordById(objid);});
				right.appendTo($("#recordHistory"));
			}else if(record.dri_id == window.backResult.driverInfo.id && record.cus_id == window.customer.id) {
				//the current record is record by current booking driver
				var left = $("<div class='left'><span class='triangle-border left'>" + timeString + "</span><img src='../images/defaultPhoto.png' width='40px' height='40px'></div>");
				left.on('tap', function() {playRecordById(objid);});
				left.appendTo($("#recordHistory"));
			}
		});
	};	
	var findAllFailure = function(err) {
		alert("findAllFailure");
		alert(JSON.stringify(err));
	};
	var options = {onSuccess: findAllSuccess, onFailure: findAllFailure}; 
	window.audioJS.count()
	.then(function(numberOfDocuments) {
		if(numberOfDocuments == 0)return;
		if(numberOfDocuments > 4) {
			window.currentOffset = options.offset = numberOfDocuments - 4;
			options.limit = 4;
//			alert("currentOffset::" + window.currentOffset);
		}
		window.audioJS.findAll(options);
	})
	.fail(function() {
		alert("count failure");
		window.audioJS.findAll(options);
	});
	
}

/**
 * get the encodedString from JSONStore according to the id and decode the audio and play it 
 */
function playRecordById(objid) {
//	alert("playRecord" + objid);
	//get the encodedString from JSONStore according to the id
	var query = {_id : objid};
	window.audioJS.find(query, {})
	.then(function(data) {
//		alert(JSON.stringify(data));
		var encodedContent = data[0].json.encodedString;
//		alert(encodedContent);
		playRecordByContent(encodedContent);
	})
	.fail(function(err) {
		alert("find fail");
		alert(JSON.stringify(err));
	});

}
/**
 * when decode success play it
 * @param result
 */
function decodeSuccess(result) {
//	alert("decodeSuccess");
	var mediaPlayer = new Media(playSrc, function() {
//		alert("playAudio():Audio new Success");
	}, function(err) {
//		alert("playAudio():Audio new Error: " + err);
	}, function(status) {
//		alert("playAudio():Audio Status: " + Media.MEDIA_MSG[status]);
	});
	mediaPlayer.play();
}

/**
 * when decode fail , remind user decode fail
 * @param result
 */
function decodeFailure(result) {
	alert("decodeFail:");
}

/**
 * add listener of voice btn
 */
$("#voiceBtn").on("tap", function(){
//	alert("tap btn");
	var currentStatus = $('#voiceBtn').data('status');
	if (currentStatus == "stop") {
//		alert("currentStatus=stop");
		$('#voiceBtn .ui-btn-text').text("stop");
		$('#voiceBtn').data('status', "running");
		startRecordAudio();
	} else if (currentStatus == "running") {
//		alert("currentStatus=running");
		$('#voiceBtn .ui-btn-text').text("record");
		$('#voiceBtn').data('status', "stop");
		stopRecordAudio();
	}
});

/**
 * add listener of more btn
 * load 6 more record once
 */
$("#moreBtn").on('tap', function() {
	var findAllSuccess = function(data) {
		alert("findAllSuccess");
		var size = data.length;
//		alert("size::" + size);
		for(var i = 1; i <= size; i++) {
//			alert("i::" + i);
			var record = data[size - i].json;
//			alert("record::" + JSON.stringify(record));
			var objid = data[size - i]._id;
//			alert(record.cus_id + " " + record.dri_id);
//			alert(window.customer.id +  " " + window.backResult.driverInfo.id);
			alert("objid:::" + objid);
			if(record.dri_id == 0 && record.cus_id == window.customer.id) {
				//the current user is costomer
				var right = $("<div class='right'><span class='triangle-border right'>" + record.recordTime + "</span><img src='../images/defaultPhoto.png' width='40px' height='40px'></div>");
				//var right = $("<div class='right'><span class='triangle-border right'>" + "ccccc</span><img src='../images/defaultPhoto.png' width='40px' height='40px'></div>");
				right.on('tap', function() {playRecordById(objid);});
				right.prependTo($("#recordHistory"));
			}else if(record.dri_id == window.backResult.driverInfo.id && record.cus_id == window.customer.id) {
				//the current record is record by current booking driver
				var left = $("<div class='left'><span class='triangle-border left'>" + record.recordTime + "</span><img src='../images/defaultPhoto.png' width='40px' height='40px'></div>");
				left.on('tap', function() {playRecordById(objid);});
				left.prependTo($("#recordHistory"));
			}
		}
	};	
	var findAllFailure = function(err) {
		alert("findAllFailure");
		alert(JSON.stringify(err));
	};
	var options = {onSuccess: findAllSuccess, onFailure: findAllFailure}; 
	window.audioJS.count()
	.then(function(numberOfDocuments) {
		if(numberOfDocuments == 0 || window.currentOffset == 0){alert("no more record");return;};
		if(window.currentOffset - 4 >= 0) {
			window.currentOffset = options.offset = window.currentOffset - 4;
			options.limit = 4;
			alert("currentOffset::" + window.currentOffset);
		} else if(window.currentOffset < 4) {
			options.limit = window.currentOffset;
			window.currentOffset = options.offset = 0;
			alert("currentOffset::" + window.currentOffset);
		}
		window.audioJS.findAll(options);
	})
	.fail(function() {
		alert("count failure");
		window.audioJS.findAll(options);
	});
});
/**
 * initialize a media to record audio
 */
function startRecordAudio() {
//	alert("startRecord");
	if (recordMedia == null) {
		var recAudioSuccess = function() {
//			alert("startRecordAudio():Audio new Success");
		};
		var recAudioError = function(err) {
//			alert("startRecordAudio():Audio Error: " + err);
		};
		var recAudioStatus = function(status) {
//			alert("startRecordAudio():Audio Status: " + Media.MEDIA_MSG[status]);
		};
		recordMedia = new Media(recordSrc, recAudioSuccess, recAudioError,
				recAudioStatus);
	}
	recordMedia.startRecord();
}

/**
 * stop record then encode the record and send out
 */
function stopRecordAudio() {
//	alert("stop record audio");
	recordMedia.stopRecord();
	addLoadingRecord();
	}

/**
 * append a voice record on voice container
 */
function addLoadingRecord() {
	loadingRecord = $("<div class='right'><span class='triangle-border right sending'>ccccc</span><img src='../images/defaultPhoto.png' width='35px' height='40px'></div>");
	loadingRecord.appendTo($("#recordHistory"));
	cordova.exec(encodeSuccess, encodeFailure, "EncodeUtilPlugin", "encodeAudio", [recordSrc]);

//	alert(document.getElementById('recordHistory').childElementCount);
}

/**
 * encode success ,save it to json store and send it to server
 * the key of the record in json store is userid_currenttime
 */
function encodeSuccess(result) {
//	alert("encodedSuccess;" + result);
	window.tmp = result;
	var encodedContent = result;
	var cus_id = window.customer.id;
	var dri_id = window.backResult.driverInfo.id;
	//save to the json store
	var time = (new Date()).getTime();
	var data = {cus_id: window.customer.id, dri_id: '0', recordTime: time, encodedString : result};
	window.audioJS.add(data, {})
	.then(function () {
//		alert("insert audio success");
		loadingRecord.on('tap', function(ec) {
			return function() {alert(ec);playRecordByContent(ec);};
		}(encodedContent));
		//send to the server
		var invocationData = {
				adapter : 'stAdp',
				procedure : 'sendAudio',
				parameters : [{'cus_id': cus_id,'dri_id':dri_id, recordTime: time, 'encodedString':result}]
		};
		WL.Client.invokeProcedure(invocationData, {
			onSuccess : sendSuccess,
			onFailure : sendFailure
		});
	})
	.fail(function (errorObject) {
		alert("insert audio fail");
	});
	
}

function playRecordByContent(encodedString) {
//	alert("playRecordByContent"+ encodedString);
	cordova.exec(decodeSuccess, decodeFailure, "EncodeUtilPlugin", "decodeAudio", [encodedString]);
}


/**
 * send audio to server success, so remind the user
 */
function sendSuccess(result) {
//	alert("send Success");
	$('.sending').text("OK");
	$('.sending').removeClass('sending');
	//just test to add the left what audio is send to server and return from server.
//	var left = $("<div class='left'><img src='../images/defaultPhoto.png' width='40px' height='40px'><span class='triangle-border left'>ccccc</span></div>");
//	alert(result.invocationResult.encodedString);
//	left.on('tap', function() {playRecordByContent(result.invocationResult.encodedString);});
//	left.prependTo($("#recordHistory"));
//	$("#recordHistory").append(left);
//	setTimeout(function() {receiveEncodeAudio('1', '123', 124, window.tmp);}, 20000);
}

/**
 * send audio to server failure, so remind the user
 */
function sendFailure() {
	$('.sending').text("fail");
	$('.sending').removeClass('sending');
//	alert("setTimeout");
	setTimeout(function() {receiveEncodeAudio('1', '123', 124, window.tmp);}, 20000);
}

/**
 * encode fail , so remind the user
 * @param result
 */
function encodeFailure(result) {
//	alert("encode fail:" + result);
}

/**
 * receive the encoded string of a audio from push notification, save it to json store
 * PS: we don't save the audio file in android SDcard ,just save the encoded string in json store 
 * decode the encoded string when playing the audio
 * @param result
 */
function receiveEncodeAudio(cus_id, dri_id, recordTime, encodedString) {
//	alert(cus_id + " " + dri_id);
//	alert(window.customer.id +  " " + window.backResult.driverInfo.id);
	
	//only handle the current return driver record
	if(dri_id == window.backResult.driverInfo.id && cus_id == window.customer.id) {
//		alert("append driver audio");
		var left = $("<div class='left'><img src='../images/defaultPhoto.png' width='40px' height='40px'><span class='triangle-border left'>driver</span></div>");
		left.on('tap', function() {playRecordByContent(encodedString);});
		left.appendTo($("#recordHistory"));
		var data = {cus_id: cus_id, dri_id: dri_id, recordTime: recordTime, encodedString : encodedString};
		window.audioJS.add(data, {})
		.then(function () {
//			alert("insert audio success");
		})
		.fail(function (errorObject) {
			alert("insert audio fail");
		});
	}
}


function receiveOrderAccept(dri_info, order_info) {
	$("#namePopup").text(dri_info.name);
	var credit = dri_info.credit;
	for(var i = 0; i < credit; i++) {
		$("<img src='../images/star.png' width='14px' height='14px' />").appendTo($("#creditPopup"));
	}
	$("#licensePopup").text(dri_info.license);
	$("#colorPopup").text(dri_info.color);
	$("#timePopup").text(order_info.time);
	$("#fromAddrPopup").text(order_info.fromAddr);
	$("#toAddrPopup").text(order_info.toAddr);
	$("#orderPopup").popup("open");
	
	$("#handleNowBtn").on('tap', function() {
		if(window.page == 0) {
			//current page is main page
			$(".cusmain").addClass("hidden");
			$(".dispOptions").addClass("hidden");
			$(".response").removeClass("hidden");
			$(".responseheader").removeClass("hidden");
			$("#mapContainer").removeClass("custMainMap");
			$("#mapContainer").addClass("responseMap");
			$(".orderTaxi").addClass("hidden");
		} 
	});
	$("#handleLaterBtn").on('tap', function() {
		$("#orderPopup").popup("close");
		//add it to my orders list
	});
	$("#orderPopup").popup("open");
}


function setBounds(pos1, pos2){

	var upperLat = Math.max(pos1.lat(),pos2.lat());
	var lowerLat = Math.min(pos1.lat(),pos2.lat());
	var rightLng = Math.max(pos1.lng(),pos2.lng());
	var leftLng = Math.min(pos1.lng(),pos2.lng());
	var upperLeftLatLng = new google.maps.LatLng(upperLat, leftLng);
	var lowerRightLatLng = new google.maps.LatLng(lowerLat, rightLng);
	var bounds = new google.maps.LatLngBounds(upperLeftLatLng, lowerRightLatLng);
    window.map.fitBounds(bounds);
}
